
import glob
import os
import xlrd
import json  # 导入模块
import time
import socket

def get_host_ip():
    try:

        try:
            # with open(os.path.join('activate/','code'),'r') as f:
            with open('static/IP', 'r') as f:
                ip = f.readline().strip().split('==')[1]
        except Exception as e:
            print("The ip file not found or type format is error !")

            s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
            s.connect(('8.8.8.8',80))
            ip=s.getsockname()[0]

            s.close()
    except:
        ip = '0.0.0.0'
    return ip
def get_meter_recog_dingdian(filename):
    position_dict = {}
    meter_recog_dict = {}

    # 打开文件
    workbook = xlrd.open_workbook(filename)
    sheet2_name = workbook.sheet_names()  # 获取所有sheet名称
    # 根据sheet索引或者名称获取sheet内容
    sheet1 = workbook.sheet_by_index(0)  # sheet索引从0开始
    # sheet1的名称，行数，列数
    print(sheet1.name, sheet1.nrows, sheet1.ncols)

    for i in range(sheet1.nrows):

        try:
            detail = str(sheet1.cell_value(i, 23))+ str(sheet1.cell_value(i, 19)) +'_' +str(sheet1.cell_value(i, 20))
            print(detail)
            tmp = [i, sheet1.cell_value(i, 1), sheet1.cell_value(i, 12), sheet1.cell_value(i, 15),
                   sheet1.cell_value(i, 16),detail]
            print('tmp',tmp)
            position_dict[sheet1.cell_value(i, 12)].append(tmp)
        except:
            position_dict[sheet1.cell_value(i, 12)] = []
            tmp = [i, sheet1.cell_value(i, 1), sheet1.cell_value(i, 12), sheet1.cell_value(i, 15),
                   sheet1.cell_value(i, 16),detail]
            position_dict[sheet1.cell_value(i, 12)].append(tmp)

    print(len(position_dict['定点识别']))

    for item in position_dict['定点识别']:
        if item[3] == 1.0 or item[3] == '':
            # print(item)
            meter_recog_dict[item[1]] = [1.0,item[-1]]

    # for item in position_dict['表计识别']:
        elif item[3] != 1.0 and item[3] != '':
            # print(item)
            meter_recog_dict[item[1]] = [item[3],item[-1]]

        else:
            print(item)

    print(len(meter_recog_dict))

    return meter_recog_dict
def get_meter_recog(filename):
    position_dict = {}
    meter_recog_dict = {}

    # 打开文件
    workbook = xlrd.open_workbook(filename)
    sheet2_name = workbook.sheet_names()  # 获取所有sheet名称
    # 根据sheet索引或者名称获取sheet内容
    sheet1 = workbook.sheet_by_index(0)  # sheet索引从0开始
    # sheet1的名称，行数，列数
    print(sheet1.name, sheet1.nrows, sheet1.ncols)

    for i in range(sheet1.nrows):

        try:
            detail = str(sheet1.cell_value(i, 16))+ str(sheet1.cell_value(i, 12)) +'_' +str(sheet1.cell_value(i, 13))
            print('detail',detail)
            tmp = [i, sheet1.cell_value(i, 1), sheet1.cell_value(i, 6), sheet1.cell_value(i, 9),
                   sheet1.cell_value(i, 10),detail]
            print('tmp',tmp)
            position_dict[sheet1.cell_value(i, 6)].append(tmp)
        except:
            position_dict[sheet1.cell_value(i, 6)] = []
            tmp = [i, sheet1.cell_value(i, 1), sheet1.cell_value(i, 6), sheet1.cell_value(i, 9),
                   sheet1.cell_value(i, 10),detail]
            position_dict[sheet1.cell_value(i, 6)].append(tmp)

    print(len(position_dict['表计识别']))

    for item in position_dict['表计识别']:
        if item[3] == 1.0 or item[3] == '':
            # print(item)
            meter_recog_dict[item[1]] = [1.0,item[-1]]

    # for item in position_dict['表计识别']:
        elif item[3] != 1.0 and item[3] != '':
            # print(item)
            meter_recog_dict[item[1]] = [item[3],item[-1]]

        else:
            print(item)

    print(len(meter_recog_dict))

    return meter_recog_dict


def get_meter_json(meter_recog_dict):
    meterDict = {}
    for meter in meter_recog_dict.keys():
        if meter_recog_dict[meter][0] ==1.0:
            tmp = {}
            tmp['info0'] = '1'
            tmp['info1'] = ''
            tmp['info2'] = ''
            tmp['info3'] = meter_recog_dict[meter][-1]
            meterDict[meter] = tmp
    for meter in meter_recog_dict.keys():
        if meter_recog_dict[meter][0] != 1.0:
            tmp = {}
            tmp['info0'] = str(meter_recog_dict[meter][0])
            tmp['info1'] = ''
            tmp['info2'] = ''
            tmp['info3'] = meter_recog_dict[meter][-1]
            meterDict[meter] = tmp
    return meterDict

def update_json(data,json_file):
    with open(json_file, 'w') as file:  # test.json文本，只能写入状态 如果没有就创建
        json.dump(data, file)  # data转换为json数据格式并写入文件
        file.close()  # 关闭文件

def read_json(json_file):
    with open(json_file, 'r') as fileR:  # 打开文本读取状态
        R = json.load(fileR)  # 解析读到的文本内容 转为python数据 以一个变量接收
        fileR.close()  # 关闭文件
    return R

def addJson(jsonfile,newDict):
    allDict  = read_json(jsonfile)

    print(allDict.keys())
    newKey = [k for k in newDict.keys()]
    allKey = [k for k in allDict.keys()]
    if newKey[0] in allKey:
        return '点位编号已经存在'
    #todo 可以加密控制上限数目
    if len(allKey) > 100:
        return '点位数目超过上限'
    allDict.update(newDict)
    update_json(allDict,jsonfile)
    return '操作成功'
def addModelJson(jsonfile,newDict):
    allDict  = read_json(jsonfile)

    newKey = [k for k in newDict.keys()]
    allKey = [k for k in allDict.keys()]
    if newKey[0] in allKey:
        return '模型编号已经存在'
    #todo 可以加密控制上限数目
    if len(allKey) > 20:
        return '模型数目已超过上限'
    allDict.update(newDict)
    update_json(allDict,jsonfile)
    return '操作成功'
def editJson(jsonfile,newDict,positionNum):
    allDict  = read_json(jsonfile)
    del allDict[positionNum]
    print(allDict.keys())
    print(allDict)
    newKey = [k for k in newDict.keys()]
    allKey = [k for k in allDict.keys()]

    if newKey[0] in allKey:
        return '点位编号已经存在'

    allDict.update(newDict)
    update_json(allDict,jsonfile)
    return '操作成功'

def delJson(jsonfile,positionNum):
    allDict  = read_json(jsonfile)
    del allDict[positionNum]
    update_json(allDict,jsonfile)
    return '操作成功'

def getTemplate(jsonfile,positionNum):
    allDict = read_json(jsonfile)

    allKey = [k for k in allDict.keys()]
    if positionNum not in allKey:
        allDict.update({positionNum:[{"info0": "","info1": "","info2": "","info3":""}]})
        update_json(allDict, jsonfile)
        output = [{'boxes': '', 'keypoints': '', 'picAdress': ''}]
    else:
        result = allDict[positionNum]
        output = []
        for template in result:
            tmpData = {}
            tmpData['boxes'] = template['info1']
            tmpData['keypoints'] = template['info1']
            if template['info2'] == "":
                tmpData['picAdress'] = ""
            else:
                tmpData['picAdress'] = 'https://127.0.0.1:8888/templates/' + template['info2']

            output.append(tmpData)
    message = '操作成功'
    return output,message
# def updateTemplate(jsonfile,positionNum,positionData):
#
#     positionData = list(positionData)
#     newDict = {}
#     dictData = []
#     i = 0
#     for template in positionData:
#         tmpData = {}
#         tmpData['info0'] = '0'
#         tmpData['info1'] = template['boxes']
#         tmpData['info1'] = template['keypoints']
#
#         pic_path = '{}_{}_{}.jpg'.format(positionNum,i,time.time())
#         # user_image = base64.b64decode(template['Pic'])
#         # img_array = np.fromstring(user_image, np.uint8)
#         # img = cv2.imdecode(img_array, cv2.COLOR_BGR2RGB)
#         # cv2.imwrite('static/templates/{}'.format(pic_path),img)
#
#
#         tmpData['info2'] = 'https://127.0.0.1:8888/templates/{}'.format(pic_path)
#         tmpData['info3'] = '0'
#         dictData.append(tmpData)
#         i+=1
#     newDict[positionNum] = dictData
#     allDict = read_json(jsonfile)
#     print(newDict)
#     print(allDict)
#     allDict.update(newDict)
#     update_json(allDict,jsonfile)
#     message = "操作成功"
#     return message
def refressJson(templatesPath = '/home/heils_lhl/Heils/youi-meter-p/templates'):
    meterDict = {}
    for item in glob.iglob(templatesPath+'/*jpg'):
        meter = item.split('/')[-1].split('-')[0]
        if os.path.exists(item[:-3]+'json'):
            # [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] =  decode(img)
            a = read_json(item[:-3]+'json')['shapes']
            boxes = ''
            for box in a:
                tmp = box['label'] + ',' + str(int(box['points'][0][0])) + ',' + str(int(box['points'][0][1])) + ',' + str(int(box['points'][1][0])) + ',' + str(int(box['points'][1][1]))+';'
                boxes+= tmp
            tmp = {}
            tmp['positionName'] = meter
            tmp['info'] = ''
            tmp['picAdress'] = ['http://192.168.1.116:8888/templates/'+item.split('/')[-1]]
            tmp['multimeter'] = '1'
            tmp['template'] = '1'
            tmp['tagbox'] = boxes[:-1]
            # tmp['info2'] = '{},{},{},{},{},{},{},{}'.format(int(x1),int(y1),int(x2),int(y2),int(x3),int(y3),int(x4),int(y4))
            tmp['image'] = item.split('/')[-1]
            tmp['detect'] = '0'
            tmp["detectcate"] = ''
            meterDict[meter] = tmp
        else:
            print(item[:-3]+'json')
            tmp = {}
            tmp['positionName'] = meter
            tmp['info'] = ''
            tmp['picAdress'] = 'http://192.168.1.116:8888/templates/'
            tmp['multimeter'] = '1'
            tmp['template'] = '1'
            tmp['tagbox'] = ''
            tmp['image'] = ''
            tmp['detect'] = '0'
            tmp["detectcate"]:''
            meterDict[meter] = tmp
    print(meterDict)
    data = meterDict
    json_file = templatesPath+'/positionManagement.json'
    update_json(data,json_file)
    return 'sucess'
def now_to_date(format_string="%Y-%m-%d %H:%M:%S"):
    time_stamp = int(time.time())
    time_array = time.localtime(time_stamp)
    str_date = time.strftime(format_string, time_array)
    return str_date
def search_model_json(dict_json,keyword):
    new_dict_json = {}
    for item in dict_json:
        if keyword in item  or keyword in dict_json[item]['modelName']:
            new_dict_json[item] = dict_json[item]
    return new_dict_json

def showfiles(path,allfiles):
    fileslist = os.listdir(path)
    for file in fileslist:
        cur_path  = os.path.join(path,file)
        if os.path.isdir(cur_path):
            showfiles(cur_path,allfiles)
        else:
            allfiles.append(cur_path)
    return allfiles

def search_position_json(dict_json,keyword):
    new_dict_json = {}
    for item in dict_json:
        if keyword in item  or keyword in dict_json[item]['positionName']:
            new_dict_json[item] = dict_json[item]
    return new_dict_json

def checkTemplates(folderPath):

    allfiles = showfiles(folderPath,[])
    jpgfiles = [i for i in allfiles if i.endswith('jpg')]
    jsonfiles = [i for i in allfiles if i.endswith('json')]
    if len(jpgfiles) == len(jsonfiles):
        return 0
    else:
        return 1
def checkData(folderPath):

    allfiles = showfiles(folderPath,[])
    jpgfiles = [i for i in allfiles if i.endswith('jpg')]
    jsonfiles = [i for i in allfiles if i.endswith('json')]
    if len(jpgfiles) == len(jsonfiles):
        return 0
    else:
        return 1


def updateTemplatesInfo(info_file,templatesFolder,json_file,ip):
    # import cv2
    meterDict = {}
    # info_file = '/home/heils_lhl/Heils/youi-meter-p/static/infoManagement.json'
    info_json = read_json(info_file)
    # for item in sorted(glob.glob('/home/heils_lhl/Heils/youi-meter-p/static/templates/*json'), key=os.path.getmtime,reverse=True):
    for item in sorted(glob.glob('{}/*json'.format(templatesFolder)), key=os.path.getmtime,reverse=True):
        meter = item.split('/')[-1].split('-')[0]
        try:
            meterName = item.split('/')[-1].split('-')[1]
        except:
            meterName = meter

        if os.path.exists(item[:-4] + 'jpg'):
            # img = cv2.imread(item[:-4] + 'jpg')
            # [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] =  decode(img)
            a = read_json(item)['shapes']
            boxes = ''
            for box in a:
                if box['shape_type'] == 'rectangle':
                    tmp = box['label'] + ',' + str(int(box['points'][0][0])) + ',' + str(
                        int(box['points'][0][1])) + ',' + str(int(box['points'][1][0])) + ',' + str(
                        int(box['points'][1][1])) + ';'
                    boxes += tmp
                    if box['label'] == '10' or box['label'] == '11':
                        print([int(box['points'][1][1]), int(box['points'][0][1]), int(box['points'][1][0]),
                               int(box['points'][0][0])])
                        # pic = img[int(box['points'][0][1]):int(box['points'][1][1]),
                        #       int(box['points'][0][0]):int(box['points'][1][0]), ]
            tmp = {}
            tmp['positionName'] = meterName
            try:
                tmp['info'] = info_json[meter]
            except:
                tmp['info'] = ''
            tmp['picAdress'] = ['http://{}:8888/static/templates/'.format(ip) + item.split('/')[-1][:-4] + 'jpg']
            tmp['multimeter'] = '1'
            tmp['template'] = '1'
            tmp['tagbox'] = boxes[:-1]
            # tmp['info2'] = '{},{},{},{},{},{},{},{}'.format(int(x1),int(y1),int(x2),int(y2),int(x3),int(y3),int(x4),int(y4))
            tmp['image'] = item.split('/')[-1][:-4] + 'jpg'
            tmp['detect'] = '0'
            tmp["detectcate"] = ''
            meterDict[meter] = tmp
            print(meter)
    print(meterDict)
    data = meterDict
    # json_file = '/home/heils_lhl/Heils/youi-meter-p/static/positionManagement.json'
    update_json(data, json_file)


if __name__ == '__main__':
    info_file = '../static/infoManagement.json'
    templatesFolder = '../static/templates'
    json_file = '../static/positionManagement.json'
    ip = '192.168.1.116'
    updateTemplatesInfo(info_file, templatesFolder, json_file,ip)
    # import cv2
    # meterDict = {}
    # info_file = '/home/heils_lhl/Heils/youi-meter-p/static/infoManagement.json'
    # info_json = read_json(info_file)
    # for item in sorted(glob.glob('/home/heils_lhl/Heils/youi-meter-p/static/templates/*json'), key=os.path.getmtime,reverse=True):
    #     meter = item.split('/')[-1].split('-')[0]
    #     try:
    #         meterName = item.split('/')[-1].split('-')[1]
    #     except:
    #         meterName = meter
    #
    #     if os.path.exists(item[:-4]+'jpg'):
    #         img = cv2.imread(item[:-4] + 'jpg')
    #         # [[x1,y1],[x2,y2],[x3,y3],[x4,y4]] =  decode(img)
    #         a = read_json(item)['shapes']
    #         boxes = ''
    #         for box in a:
    #             if box['shape_type'] =='rectangle':
    #                 tmp = box['label'] + ',' + str(int(box['points'][0][0])) + ',' + str(int(box['points'][0][1])) + ',' + str(int(box['points'][1][0])) + ',' + str(int(box['points'][1][1]))+';'
    #                 boxes+= tmp
    #                 if box['label'] =='10'or box['label'] =='11':
    #
    #                     print([int(box['points'][1][1]),int(box['points'][0][1]),int(box['points'][1][0]),int(box['points'][0][0])])
    #                     # pic = img[int(box['points'][0][1]):int(box['points'][1][1]),int(box['points'][0][0]):int(box['points'][1][0]),]
    #                     ## 相似度图片用png，好区分
    #                     # pic_name = '/home/heils_lhl/Heils/youi-meter-p/meter_recognition/meterSmilar/'+  box['label']+'_'+ str(box['group_id']) +'.png'
    #                     # cv2.imwrite(pic_name,pic)
    #                     # cv2.imshow('pic',pic)
    #                     # cv2.waitKey(0)
    #         ## todo 多指针仪表下的处理
    #         tmp = {}
    #         tmp['positionName'] = meterName
    #         try:
    #             tmp['info'] = info_json[meter]
    #         except:
    #         tmp['template'] = '1'
    #         tmp['tagbox'] = boxes[:-1]
    #         # tmp['info2'] = '{},{},{},{},{},{},{},{}'.format(int(x1),int(y1),int(x2),int(y2),int(x3),int(y3),int(x4),int(y4))
    #         tmp['image'] = item.split('/')[-1][:-4] + 'jpg'
    #         tmp['detect'] = '0'
    #         tmp["detectcate"] = ''
    #         meterDict[meter] = tmp
    #         print(meter)
    #     # else:
    #     #     print(item[:-3]+'json')
    #     #     tmp = {}
    #     #     tmp['positionName'] = meter
    #     #     tmp['info'] = ''
    #     #     tmp['picAdress'] = 'http://47.106.227.179:8888/static/templates/'
    #     #     tmp['multimeter'] = '1'
    #     #     tmp['template'] = '1'
    #     #     tmp['tagbox'] = ''
    #     #     tmp['image'] = ''
    #     #     tmp['detect'] = '0'
    #     #     tmp["detectcate"]:''
    #     #     meterDict[meter] = tmp
    # print(meterDict)
    # # # format to info0,info1...
    # # # add multimeter tag
    # # meterDict = get_meter_json(meter_recog_dict)
    # #
    # #
    # #
    # data = meterDict
    # json_file = '/home/heils_lhl/Heils/youi-meter-p/static/positionManagement.json'
    # update_json(data,json_file)
    # #
    # # R = read_json(json_file)
    # # print(len(R))               tmp['info'] = ''
    #         tmp['picAdress'] = ['http://192.168.1.116:8888/static/templates/'+item.split('/')[-1][:-4] + 'jpg']
    #         tmp['multimeter'] = '1'
    #         tmp['template'] = '1'
    #         tmp['tagbox'] = boxes[:-1]
    #         # tmp['info2'] = '{},{},{},{},{},{},{},{}'.format(int(x1),int(y1),int(x2),int(y2),int(x3),int(y3),int(x4),int(y4))
    #         tmp['image'] = item.split('/')[-1][:-4] + 'jpg'
    #         tmp['detect'] = '0'
    #         tmp["detectcate"] = ''
    #         meterDict[meter] = tmp
    #         print(meter)
    #     # else:
    #     #     print(item[:-3]+'json')
    #     #     tmp = {}
    #     #     tmp['positionName'] = meter
    #     #     tmp['info'] = ''
    #     #     tmp['picAdress'] = 'http://47.106.227.179:8888/static/templates/'
    #     #     tmp['multimeter'] = '1'
    #     #     tmp['template'] = '1'
    #     #     tmp['tagbox'] = ''
    #     #     tmp['image'] = ''
    #     #     tmp['detect'] = '0'
    #     #     tmp["detectcate"]:''
    #     #     meterDict[meter] = tmp
    # print(meterDict)
    # # # format to info0,info1...
    # # # add multimeter tag
    # # meterDict = get_meter_json(meter_recog_dict)
    # #
    # #
    # #
    # data = meterDict
    # json_file = '/home/heils_lhl/Heils/youi-meter-p/static/positionManagement.json'
    # update_json(data,json_file)
    # #
    # # R = read_json(json_file)
    # # print(len(R))